package pers.cj.pdos.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.cj.pdos.controller.base.BaseController;
import pers.cj.pdos.controller.entity.ResponseData;
import pers.cj.pdos.controller.entity.ResponseEntity;
import pers.cj.pdos.controller.entity.ResponseList;
import pers.cj.pdos.entity.*;
import pers.cj.pdos.service.IHouseService;
import pers.cj.pdos.service.IRoleService;
import pers.cj.pdos.service.IStoreService;
import pers.cj.pdos.service.IUserService;
import pers.cj.pdos.utils.*;
import pers.cj.pdos.vo.HouseVo;
import pers.cj.pdos.vo.PasswordVo;
import pers.cj.pdos.vo.UserVo;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chenj
 * @since 2019-11-04
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IHouseService houseService;

    @ResponseBody
    @RequestMapping("/getAdmin")
    public ResponseData getAdmin(){
        Company company = getCompany();
        return ResponseData.success(userService.getAdminByCompany(company));
    }

    @RequiresPermissions("user:query")
    @RequestMapping("/user")
    public String user() {
        return "user/user";
    }

    @RequiresPermissions("user:insert")
    @RequestMapping("/userNew")
    public String userNew() {
        return "user/userNew";
    }

    @RequestMapping("/userChangePassword")
    public String userChangePassword(String userId,Model model) {
        model.addAttribute("id",userId);
        return "user/userChangePassword";
    }

    @RequiresPermissions("user:insert")
    @RequestMapping("/userEdit")
    public String userEdit(String userId,Model model){
        model.addAttribute("id",userId);
        return "user/userEdit";
    }

    @ResponseBody
    @RequestMapping("/user/getVoById")
    public ResponseData getVoById(String id) {
        UserVo userVo =  userService.getVoById(id);
        return ResponseData.success(userVo);
    }

    @ResponseBody
    @RequiresPermissions("user:query")
    @RequestMapping("/user/getUsers")
    public ResponseList getUsers(int page, int limit, String searchStoreId, String searchContent) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<UserVo> list = userService.listVoPage(page,limit, company.getId(), PdosUtils.getViewOtherStoreId(userVo, searchStoreId), searchContent,null);
        return ResponseList.success(userService.count(company.getId(),PdosUtils.getViewOtherStoreId(userVo, searchStoreId), searchContent,null), list);
    }

    @ResponseBody
    @RequiresPermissions("user:insert")
    @RequestMapping("/user/add")
    public ResponseEntity add(@RequestBody UserVo userVo){
        Company company = getCompany();
        User user = DataUtil.genEntityFromVo(User.class,userVo);
        DataUtil.processEntity(company,user);
        String salt = AlgorithmUtil.getCode(8,null, true,true);
        String passwordMd5 = MD5Utils.md5(user.getPassword(),1,salt);
        user.setPassword(passwordMd5);
        user.setSalt(salt);

        Map<String,Object> map = new HashMap<>();
        map.put("userId", user.getId());
        List<UserRole> userRoleList = userVo.getUserRoleList();
        DataUtil.processList(company,userRoleList, map);

        List<UserHouse> userHouseList = userVo.getUserHouseList();
        DataUtil.processList(company,userHouseList, map);

        userService.insert(user,userRoleList,userHouseList);

        return ResponseEntity.success();
    }

    @ResponseBody
    @RequiresPermissions("user:delete")
    @RequestMapping("/user/delete")
    public ResponseEntity delete(@RequestBody User user){
        Company company = getCompany();
        user.setCompanyId(company.getId());
        if (userService.check(user.getId())) {
            return ResponseEntity.fail("有业务关联，无法删除");
        }
        userService.remove(user);
        return ResponseEntity.success();
    }

    @ResponseBody
    @RequiresPermissions("user:insert")
    @RequestMapping("/user/update")
    public ResponseEntity update(@RequestBody UserVo userVo) {
        Company company = getCompany();
        User admin = userService.getAdminByCompany(company);

        User user = DataUtil.genEntityFromVo(User.class,userVo);
        if (admin.getId().equals(userVo.getId())){
            userService.updateById(user);
        } else {
            DataUtil.processEntity(false,company,user);

            //被使用，且状态变成停用
            if (user.getStatus()!=1 && userService.check(user.getId())) {
                return ResponseEntity.fail("已被使用，无法停用");
            }

            Map<String,Object> map = new HashMap<>();
            map.put("userId", user.getId());

            List<UserRole> userRoleList = userVo.getUserRoleList();
            DataUtil.processList(company,userRoleList, map);

            List<UserHouse> userHouseList = userVo.getUserHouseList();
            DataUtil.processList(company,userHouseList, map);

            userService.update(user,userRoleList,userHouseList);
        }
        return ResponseEntity.success();
    }

    @ResponseBody
    @RequiresPermissions("set:set")
    @RequestMapping("/user/checkUsername")
    public ResponseEntity checkUsername(String username) throws UnsupportedEncodingException {
        boolean exist = userService.checkUsername(URLDecoder.decode(username,"UTF-8"));
        return exist ?  new ResponseEntity(1,"用户名已被使用") : new ResponseEntity(2,"用户名为被使用");
    }

    @ResponseBody
    @RequestMapping("/user/changePassword")
    public ResponseEntity changePassword(@RequestBody PasswordVo passwordVo){
        User checkUser = userService.getById(passwordVo.getId());
        String passwordMd5 = MD5Utils.md5(passwordVo.getOldPassword(),1,checkUser.getSalt());
        if (!passwordMd5.equals(checkUser.getPassword())){
            return ResponseEntity.fail("原密码错误");
        }

        User user = new User();
        user.setId(passwordVo.getId());
        String passMd5 = MD5Utils.md5(passwordVo.getPassword(),1,checkUser.getSalt());
        user.setPassword(passMd5);
        userService.updateById(user);

        return ResponseEntity.success();
    }

    @ResponseBody
    @RequestMapping("/user/getAll")
    public ResponseData getAll() {
        UserVo userVo = getLoginUserVo();
        // 不能查看他人单据，则只能获取用户他自己本身
        if (!PdosUtils.getBoolean(userVo.getViewOtherOrder())){
            List<User> list = new ArrayList<>();
            list.add(userVo);
            return ResponseData.success(list);
        }

        // 可以查看他人单据的则可以取得他人的信息
        String storeId = PdosUtils.getViewOrderStoreId(userVo,null);
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().eq("company_id",getCompany().getId()).ne("id",getLoginUserId());
        if (!Utils.isEmpty(storeId)) {
            queryWrapper.eq("store_id",storeId);
        }
        List<User> list = userService.list(queryWrapper);
        List<User> newList = new ArrayList<>();
        newList.add(userVo);
        if (!Utils.isEmpty(list)) {
            for (User entity : list) {
                newList.add(entity);
            }
        }
        return ResponseData.success(newList);
    }

    @ResponseBody
    @RequestMapping("/user/getLoginData")
    public ResponseData getLoginData() {
        return ResponseData.success(SecurityUtils.getSubject().getPrincipal());
    }
}
